from typing import List

class Solution:
    def countSubarrays(self, nums: List[int], minK: int, maxK: int) -> int:
        max_h = 0
        min_h = 1000001
        max_i, min_i = -1, -1
        s = -1
        ans = 0
        for i, v in enumerate(nums):
            if v >= minK and v <= maxK:
                if v >= max_h:
                    max_h = v
                    max_i = i
                if v <= min_h:
                    min_h = v
                    min_i = i
                if max_h == maxK and min_h == minK:
                    ans += min(min_i, max_i) - s
            else:
                s = i
                max_h = 0
                min_h = 1000001
        return ans
    
nums = [1,3,5,2,7,5]
minK = 1
maxK = 5
so = Solution()
so.countSubarrays(nums, minK, maxK)

